import 'package:blurb/common/routers/names.dart';
import 'package:blurb/common/values/svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:blurb/common/store/user_store.dart';
import 'package:blurb/common/store/share_store.dart';
import 'package:blurb/common/models/user.dart';
import 'package:blurb/common/models/share.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:blurb/common/values/images.dart';

class PersonalPage extends StatefulWidget {
  const PersonalPage({super.key});

  @override
  State<PersonalPage> createState() => _PersonalPageState();
}

class _PersonalPageState extends State<PersonalPage> {
  List<Share> userShares = [];
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    // 在初始化时加载用户分享
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadUserShares();
    });
  }

  Future<void> _loadUserShares() async {
    final userStore = Provider.of<UserStore>(context, listen: false);
    final shareStore = Provider.of<ShareStore>(context, listen: false);
    
    if (userStore.currentUser != null) {
      setState(() {
        isLoading = true;
      });
      
      try {
        final shares = await shareStore.getUserShares(userStore.currentUser!.id);
        setState(() {
          userShares = shares;
        });
      } finally {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final userStore = Provider.of<UserStore>(context);

    return Scaffold(
      // 使用Container和DecorationImage替换backgroundColor
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MIP.background),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Observer(
            builder: (_) {
              final User? currentUser = userStore.currentUser;

              // 根据登录状态显示不同的内容
              if (currentUser != null) {
                // 已登录状态
                return RefreshIndicator(
                  onRefresh: _loadUserShares,
                  child: SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    child: Column(
                      children: [
                        _buildAppBar(context, true),
                        _buildProfileInfo(context, currentUser),
                        SizedBox(height: 20.h),
                        _buildDivider(),
                        _buildReleaseHeader(),
                        isLoading
                            ? _buildLoadingIndicator()
                            : userShares.isEmpty
                                ? _buildEmptySharesMessage()
                                : _buildUserShares(),
                      ],
                    ),
                  ),
                );
              } else {
                // 未登录状态
                return Column(
                  children: [
                    _buildAppBar(context, false),
                    _buildNotLoggedInContent(context),
                  ],
                );
              }
            },
          ),
        ),
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 30.h),
      child: const Center(
        child: CircularProgressIndicator(
          color: Color(0xFF60C3FF),
        ),
      ),
    );
  }

  Widget _buildEmptySharesMessage() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 30.h),
      child: Center(
        child: Column(
          children: [
            Image.asset(MIP.empty, width: 150.w, height: 150.h),
            SizedBox(height: 16.h),
            Text(
              'You haven\'t released any shares',
              style: GoogleFonts.inter(
                color: Colors.white70,
                fontSize: 16.sp,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUserShares() {
    return Column(
      children: userShares.map((share) => _buildShareItem(share)).toList(),
    );
  }

  Widget _buildShareItem(Share share) {
    // 格式化时间
    final DateTime shareTime = DateTime.parse(share.time);
    final String formattedTime = _formatShareTime(shareTime);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.h),
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: const Color(0xFF1F1F21),
        borderRadius: BorderRadius.circular(19.r),
        border: Border.all(color: Colors.white.withOpacity(0.1)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Observer(
                builder: (_) {
                  final userStore = Provider.of<UserStore>(context);
                  final User? currentUser = userStore.currentUser;
                  final String avatar = currentUser?.avatar ?? MIP.avatar;

                  return Container(
                    width: 48.w,
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: const Color(0xFF60C3FF).withOpacity(0.7),
                        width: 1.5.w,
                      ),
                    ),
                    child: ClipOval(
                      child: Image.asset(avatar, fit: BoxFit.cover),
                    ),
                  );
                },
              ),
              SizedBox(width: 8.w),
              Observer(
                builder: (_) {
                  final userStore = Provider.of<UserStore>(context);
                  final User? currentUser = userStore.currentUser;
                  final String nickname = currentUser?.nickname ?? 'User';

                  return Text(
                    nickname,
                    style: GoogleFonts.racingSansOne(
                      fontSize: 24.sp,
                      fontWeight: FontWeight.normal,
                      color: Colors.white,
                    ),
                  );
                },
              ),
              SizedBox(width: 10.w),
              Text(
                formattedTime,
                style: GoogleFonts.inter(
                  fontSize: 12.sp,
                  fontWeight: FontWeight.normal,
                  color: Colors.white,
                ),
              ),
            ],
          ),
          SizedBox(height: 10.h),
          Text(
            share.description,
            style: GoogleFonts.inter(
              fontSize: 14.sp,
              fontWeight: FontWeight.normal,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 10.h),
          ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(
              share.picture,
              fit: BoxFit.cover,
              width: double.infinity,
              height: 200.h,
            ),
          ),
          SizedBox(height: 8.h),
          Row(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                decoration: BoxDecoration(color: Colors.transparent),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Icon(MSI.collection, color: Colors.white, size: 24.sp),
                    SizedBox(width: 6.w),
                    Text(
                      '13',
                      style: GoogleFonts.inter(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.normal,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(width: 4.w),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                decoration: BoxDecoration(color: Colors.transparent),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Icon(MSI.comment, color: Colors.white, size: 24.sp),
                    SizedBox(width: 6.w),
                    Text(
                      '13',
                      style: GoogleFonts.inter(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.normal,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              Spacer(),
              IconButton(
                icon: Icon(MSI.report, color: Colors.white, size: 24.sp),
                onPressed: () {
                  // 删除分享
                  _showDeleteConfirmDialog(share.id);
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _showDeleteConfirmDialog(int shareId) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.grey[900],
        title: Text(
          'Delete share',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 20.sp,
          ),
        ),
        content: Text(
          'Are you sure you want to delete this share?',
          style: GoogleFonts.inter(
            color: Colors.white70,
            fontSize: 16.sp,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: GoogleFonts.inter(
                color: Colors.white70,
                fontSize: 16.sp,
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              await _deleteShare(shareId);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF60C3FF),
            ),
            child: Text(
              'Delete',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontSize: 16.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _deleteShare(int shareId) async {
    final shareStore = Provider.of<ShareStore>(context, listen: false);
    
    setState(() {
      isLoading = true;
    });
    
    try {
      final success = await shareStore.deleteShare(shareId);
      if (success) {
        // 重新加载用户分享
        await _loadUserShares();
      }
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  String _formatShareTime(DateTime shareTime) {
    final DateTime now = DateTime.now();
    final Duration difference = now.difference(shareTime);

    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()} years ago';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }

  // 构建应用栏，根据登录状态决定设置按钮行为
  Widget _buildAppBar(BuildContext context, bool isLoggedIn) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.0.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(width: 40.w), // 左侧空白，保持平衡
          Text(
            'Personal',
            style: GoogleFonts.racingSansOne(
              color: Colors.white,
              fontSize: 24.sp,
              fontWeight: FontWeight.normal,
            ),
          ),
          IconButton(
            icon: Icon(MSI.settings, color: Colors.white, size: 30.sp),
            onPressed: () {
              if (isLoggedIn) {
                // 已登录，直接跳转到设置页面
                GoRouter.of(context).push(RNS.settings);
              } else {
                // 未登录，显示提示对话框
                _showLoginDialog(context);
              }
            },
          ),
        ],
      ),
    );
  }

  // 显示登录提示对话框
  void _showLoginDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF1F1F21),
        title: Text(
          'Please login first',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: GoogleFonts.racingSansOne(
                color: Colors.white70,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              GoRouter.of(context).push(RNS.guide);
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.96),
                  colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                ),
                borderRadius: BorderRadius.circular(30.r),
              ),
            child: Text(
              'Go to login',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建未登录状态的内容
  Widget _buildNotLoggedInContent(BuildContext context) {
    return Expanded(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(MIP.empty, width: 200.w, height: 200.h),
            SizedBox(height: 20.h),
            Text(
              'Please login to view your personal page',
              style: GoogleFonts.inter(color: Colors.white70, fontSize: 16.sp),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 30.h),
            GestureDetector(
              onTap: () => context.go(RNS.guide),
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 12.h),
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    begin: Alignment(0.50, 0.00),
                    end: Alignment(0.50, 0.96),
                    colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                  ),
                  borderRadius: BorderRadius.circular(30.r),
                ),
                child: Text(
                  'Go to login',
                  style: GoogleFonts.racingSansOne(
                    color: Colors.white,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.normal,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProfileInfo(BuildContext context, User? user) {
    // 使用默认值，以防user为null
    final avatar = user?.avatar ?? MIP.avatar;
    final nickname = user?.nickname ?? 'Mindun';
    final sign =
        user?.sign ??
        'A touch of sweetness melts away all the ordinariness and troubles.';

    return Padding(
      padding: EdgeInsets.only(left: 20.0.w, right: 20.0.w, top: 20.0.h),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                width: 80.w,
                height: 80.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(color: Colors.blue, width: 2),
                  image: DecorationImage(
                    // 如果avatar是资源路径，使用AssetImage，否则使用NetworkImage
                    image: avatar.startsWith('assets/')
                        ? AssetImage(avatar) as ImageProvider
                        : NetworkImage(avatar),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(width: 20.w),
              Expanded(
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        _buildStatRow('543', 'Heat'),
                        SizedBox(width: 10.w),
                        _buildStatRow('79', 'Follow'),
                        SizedBox(width: 10.w),
                        _buildStatRow('79', 'Like'),
                      ],
                    ),
                    SizedBox(height: 10.w),
                    OutlinedButton.icon(
                      onPressed: () {
                        GoRouter.of(context).push(RNS.information);
                      },
                      icon: Icon(MSI.edit, color: Colors.white, size: 16.sp),
                      label: Text('Modify information'),
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        side: BorderSide(color: Colors.white38),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20.r),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(height: 15.h),
          Align(
            alignment: Alignment.centerLeft,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  nickname,
                  style: GoogleFonts.racingSansOne(
                    color: Colors.white,
                    fontSize: 22.sp,
                    fontWeight: FontWeight.normal,
                  ),
                ),
                SizedBox(height: 5.h),
                Text(
                  sign,
                  style: GoogleFonts.inter(
                    color: Colors.white70,
                    fontSize: 14.sp,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatRow(String count, String label) {
    return Row(
      children: [
        Text(
          count,
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 22.sp,
            fontWeight: FontWeight.normal,
          ),
        ),
        SizedBox(width: 5.w),
        Text(
          label,
          style: GoogleFonts.racingSansOne(
            color: Colors.white70,
            fontSize: 14.sp,
          ),
        ),
      ],
    );
  }

  Widget _buildDivider() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.0.w),
      child: Divider(color: Colors.white24, thickness: 1),
    );
  }

  Widget _buildReleaseHeader() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.0.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'Release',
            style: GoogleFonts.racingSansOne(
              color: Colors.white,
              fontSize: 22.sp,
              fontWeight: FontWeight.normal,
            ),
          ),
          IconButton(
            icon: Icon(Icons.add_circle_outline, color: Colors.white, size: 24.sp),
            onPressed: () {
              // 跳转到添加分享页面
              // 这里可以添加跳转逻辑
            },
          ),
        ],
      ),
    );
  }
}